package com.why.controller;

import com.why.commonresults.Result;
import com.why.service.MsmService;
import com.why.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Stack;
import java.util.concurrent.TimeUnit;

/**
 * @program: guli_parent
 * @description: 短信
 * @author: @why
 * @create: 2021-02-15 17:11
 **/
@RestController
@RequestMapping("/servicemsm/msm")
@CrossOrigin
public class MsmController {
    @Autowired
    private MsmService service;

    @Autowired
    private RedisTemplate<String, String> redis;

    @GetMapping("/send/{phoneNumber}")
    public Result smsController(@PathVariable String phoneNumber) {

        //电话号码长度判断
//        if (phoneNumber.length() != 11) {
//            return Result.error();
//        }
        //1.先从redis中看看有无短信,使用手机号作为key
        String beforeCode = redis.opsForValue().get(phoneNumber);
        if (!StringUtils.isEmpty(beforeCode)) {
            return Result.ok().message("短信已经发送给该手机号码！");
        } else {
        //2. redis中无该手机号的短信

            //生成随机的验证码传递给阿里云
            String code = RandomUtils.getFourBitRandom();
            HashMap<String, String> map = new HashMap<>();
            map.put("code", code);
            //发送短信
            boolean flag = service.sendSMS(map, phoneNumber);
            //保存到redis
            if (flag) {
                //保存并设置5分钟有效时长
                redis.opsForValue().set(phoneNumber, code,5, TimeUnit.MINUTES);
            }
            return flag ? Result.ok() : Result.error().message("短信发送失败！");
        }


    }
}
